package com.yunfeisoft.controller.interceptor;

import com.applet.session.SessionModel;
import com.applet.session.UserSession;
import com.applet.utils.AjaxUtils;
import com.applet.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 采集日志拦截器
 * Created by Jackie Liu on 2017/7/10.
 */
public class ApiInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private UserSession userSession;

    private AntPathMatcher pathMatcher = new AntPathMatcher();
    //private String controllerPath = "/api/**";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*String[] allowDomains = {"http://localhost:8080", "http://192.168.1.7:8080"};
        Set allowOrigins = new HashSet(Arrays.asList(allowDomains));
        String originHeads = request.getHeader("Origin");
        if (allowOrigins.contains(originHeads)) {
            response.setHeader("Access-Control-Allow-Origin", originHeads);
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin,x-requested-with");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            if (request.getMethod().toUpperCase().equals("OPTIONS")) {
                response.setStatus(200);
                return false;
            }
        }*/

        /*String uri = request.getRequestURI().replaceFirst(request.getContextPath(), "");
        if (uri.indexOf("loginIn.json") >= 0) {
            return true;
        }*/
        /*if (!pathMatcher.match(this.controllerPath, uri)) {
            return true;
        }*/
        SessionModel sessionModel = userSession.getSessionModel();
        if (sessionModel != null) {
            request.setAttribute(Constants.SESSION_MODEL, sessionModel);
            userSession.resetSessionTime();
            return true;
        }
        AjaxUtils.ajaxJsonErrorMessage("100010001");
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}
